package com.chain.BrotherExchange.viewmodel;

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.MutableLiveData;
import android.content.res.Resources;
import android.support.annotation.NonNull;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.DataRepository;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.BaseResponseModel;
import com.chain.BrotherExchange.data.model.EntrustQueue;
import com.chain.BrotherExchange.data.model.SingleCoinBalance;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.utils.EncryptionUtils;
import com.chain.BrotherExchange.utils.Strings;

import java.text.DecimalFormat;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * 币币
 */
public class CoinViewModel extends AndroidViewModel {

//    private final int uid = Androids.LocalConfig.getUid();
//    private final String token = Androids.LocalConfig.getToken();

    // 当前选中交易对符号
    private String mSymbol;

    // 选择买卖盘数据
    private EntrustQueue.DataBean.Bean mSelectBuyData, mSelectSellData;
    // 最低买卖盘数据
    private EntrustQueue.DataBean.Bean mLowestBuyData, mLowestSellData;

    // 买入ID/卖出ID
    private String mPurchaseTokenId, mSellTokenId;

    // 交易类型：买入/卖出
    private int mTransactionType = C.API_ENTRUST_BUY;
    // 委托类型：限价或市价
    private int mEntrustType = C.API_LIMITED_PRICE;

    // 可购买与可用货币符号
    private String mFirstTradingPairSymbols = "", mSecondTradingPairSymbols = "";

    // 用户可用余额:买入和卖出
    private double mBuyAvailableBalance, mSellAvailableBalance;

    // 可买或可卖数量
    private double mPurchasableOrSellNumber;
    // 当前可买或可卖数量百分比
    private double mActualPurchasableNumberPercent;
    // 折合价格及折合数量
    private double mEquivalentPrice, mEquivalentNumber;

    private MutableLiveData<String> mEquivalentPriceCall = new MutableLiveData<>();
    private MutableLiveData<String> mAvailableBalanceCall = new MutableLiveData<>();
    private MutableLiveData<String> mNumberTokenSymbolCall = new MutableLiveData<>();
    private MutableLiveData<String> mPurchasableUnitPriceCall = new MutableLiveData<>();
    private MutableLiveData<String> mActualPurchasableNumberCall = new MutableLiveData<>();
    private MutableLiveData<String> mPurchasableOrSellNumberCall = new MutableLiveData<>();
    private MutableLiveData<Resource<BaseResponseModel>> mEntrustOrdersLiveData = new MutableLiveData<>();
    private MutableLiveData<Resource<EntrustQueue.DataBean>> mEntrustQueueLiveData = new MutableLiveData<>();

    public CoinViewModel(@NonNull Application application) {
        super(application);
        mSelectBuyData = mSelectSellData = mLowestBuyData = mLowestSellData = EntrustQueue.createEmpty();
    }

    public MutableLiveData<String> getNumberTokenSymbol() {
        return mNumberTokenSymbolCall;
    }

    // 折合价格
    public MutableLiveData<String> equivalentPrice() {
        return mEquivalentPriceCall;
    }

    // 获取买卖盘
    public MutableLiveData<Resource<EntrustQueue.DataBean>> entrustQueue() {
        return mEntrustQueueLiveData;
    }

    // 获取可买数量
    public MutableLiveData<String> purchasableNumber() {
        return mPurchasableOrSellNumberCall;
    }

    // 真实购买数量
    public MutableLiveData<String> actualPurchasableNumber() {
        return mActualPurchasableNumberCall;
    }

    // 折合数量
    public MutableLiveData<String> equivalentNumber() {
        return mPurchasableUnitPriceCall;
    }

    // 设置折合数量
    public void setEquivalentNumber(String number) {
        if (!Strings.isEmpty(number)) {
            double newEquivalentNumber = Double.parseDouble(number);
            if (newEquivalentNumber > 0) {
                // 新折合价格
                if (mEquivalentPrice > 0) {
                    mEquivalentPriceCall.setValue(new DecimalFormat("#########.##").format(
                            ((mEquivalentPrice / mEquivalentNumber) * newEquivalentNumber)));
                }

                // 可买或可卖数量
                if(mTransactionType == C.API_ENTRUST_BUY){
                    mPurchasableOrSellNumber = mBuyAvailableBalance / newEquivalentNumber;
                } else {
                    mPurchasableOrSellNumber = mSellAvailableBalance * newEquivalentNumber;
                }

//                mPurchasableOrSellNumber =
//                        (mTransactionType == C.API_ENTRUST_BUY ? mBuyAvailableBalance : mSellAvailableBalance)
//                                / newEquivalentNumber;
                loadPurchasableOrSellNumber(mPurchasableOrSellNumber);
            }
        }
    }

    public MutableLiveData<String> availableBalance() {
        return mAvailableBalanceCall;
    }

    // 选择购买数量百分比
    public void purchasableNumberPercent(double percent) {
        mActualPurchasableNumberPercent = percent;
        if ((mPurchasableOrSellNumber * percent) > 0) {
            mActualPurchasableNumberCall.setValue(new DecimalFormat("#########.########")
                    .format(mPurchasableOrSellNumber * percent)
            );
        }
    }

    // 获取买卖盘委托记录列表
    public void requestEntrustedRecordList(String symbol, int purchaseTokenId, int sellTokenId) {
        mSymbol = symbol;
        mFirstTradingPairSymbols = mSymbol.split("/")[0];
        mSecondTradingPairSymbols = mSymbol.split("/")[1];
        mPurchaseTokenId = String.valueOf(purchaseTokenId);
        mSellTokenId = String.valueOf(sellTokenId);

        mEntrustQueueLiveData.setValue(Resource.loading());
        DataRepository.get().entrustQueue(symbol, result -> {
            EntrustQueue.DataBean resultData = result.getData();
            if (resultData != null && result.isSucceed()) {
                mEntrustQueueLiveData.setValue(Resource.success(resultData));
                initDefaultAndMinEntrusted(resultData);
            } else if (result.isNotNetwork()) {
                mEntrustQueueLiveData.setValue(Resource.notNetwork());
            } else {
                mEntrustQueueLiveData.setValue(Resource.error(result.getMsg()));
            }
        });
    }

    // 初始化默认和选中的买卖盘
    private void initDefaultAndMinEntrusted(EntrustQueue.DataBean resultData) {
        // 默认选择买盘为最低
        List<EntrustQueue.DataBean.Bean> buyOrderList = resultData.getBuy();
        if (buyOrderList != null && !buyOrderList.isEmpty()) {
            Collections.sort(buyOrderList);
            mSelectBuyData = mLowestBuyData = buyOrderList.get(0);
        } else {
            mSelectBuyData = mLowestBuyData = EntrustQueue.createEmpty();
        }

        // 默认选择建议买盘为最低
        List<EntrustQueue.DataBean.Bean> sellOrderList = resultData.getSell();
        if (sellOrderList != null && !sellOrderList.isEmpty()) {
            Collections.sort(sellOrderList);
            mSelectSellData = mLowestSellData = sellOrderList.get(0);
        } else {
            mSelectSellData = mLowestSellData = EntrustQueue.createEmpty();
        }

        requestAvailableBalance();
    }

    // 可用余额
    private void requestAvailableBalance() {
        int uid = Androids.LocalConfig.getUid();
        String token = Androids.LocalConfig.getToken();

        // 买入余额
        DataRepository.get().singleCoinBalance(uid, token, mPurchaseTokenId, result -> {
            SingleCoinBalance.DataBean resultData = result.getData();
            if (result.isSucceed() && resultData != null) {
                mBuyAvailableBalance = Double.parseDouble(resultData.getBalance().getBalance());
                loadSelectBuyOrPurchasableOrder();
            }
        });

        // 卖出余额
        DataRepository.get().singleCoinBalance(uid, token, mSellTokenId, result -> {
            SingleCoinBalance.DataBean resultData = result.getData();
            if (result.isSucceed()) {
                mSellAvailableBalance = Double.parseDouble(resultData.getBalance().getBalance());
                loadSelectBuyOrPurchasableOrder();
            }
        });
    }

    // 加载选择买卖盘
    private void loadSelectBuyOrPurchasableOrder() {
        // 可用余额
        EntrustQueue.DataBean.Bean bean;
        if (mEntrustType == C.API_LIMITED_PRICE) { // 限价委托
            bean = mTransactionType == C.API_ENTRUST_BUY ? mSelectBuyData : mSelectSellData;
        } else { // 市价委托-最低价
            bean = mTransactionType == C.API_ENTRUST_BUY ? mLowestBuyData : mLowestSellData;
        }

        // 折合数量
        mEquivalentNumber = Double.parseDouble(bean.getOn_price());
        mPurchasableUnitPriceCall.setValue(bean.getOn_price());

        // 折合价格
        mEquivalentPrice = Double.parseDouble(bean.getCny_price());
        mEquivalentPriceCall.setValue(bean.getCny_price());

        // 可买数量
        if (mEquivalentNumber > 0) {
            if( mTransactionType == C.API_ENTRUST_BUY){
                mPurchasableOrSellNumber = mBuyAvailableBalance / mEquivalentNumber;
            } else {
                mPurchasableOrSellNumber = mSellAvailableBalance * mEquivalentNumber;
            }
            //mPurchasableOrSellNumber = availableBalance / mEquivalentNumber;
            loadPurchasableOrSellNumber(mPurchasableOrSellNumber);
        } else {
            loadPurchasableOrSellNumber(0);
        }

        // 买或卖货币符号
        mNumberTokenSymbolCall.setValue(mFirstTradingPairSymbols);

        // 可用余额
        double availableBalance = mTransactionType == C.API_ENTRUST_BUY
                ? mBuyAvailableBalance : mSellAvailableBalance;
        loadAvailableBalance(availableBalance);

        // 真实购买数量
        purchasableNumberPercent(mActualPurchasableNumberPercent);
    }

    // 加载可卖或可买数量
    private void loadPurchasableOrSellNumber(double purchasableOrSellNumber) {
        String symbol = mTransactionType == C.API_ENTRUST_BUY ? mFirstTradingPairSymbols
                : mSecondTradingPairSymbols;
        Resources resources = getApplication().getResources();
        mPurchasableOrSellNumberCall.setValue(String.format(
                resources.getString(R.string.placeholder_purchasable_balance),
                new DecimalFormat("########.########").format(purchasableOrSellNumber),
                symbol)
        );
    }

    // 加载可用余额
    private void loadAvailableBalance(double availableBalance) {
        String symbol = mTransactionType == C.API_ENTRUST_BUY ? mSecondTradingPairSymbols
                : mFirstTradingPairSymbols;
        Resources resources = getApplication().getResources();
        mAvailableBalanceCall.setValue(String.format(
                resources.getString(R.string.placeholder_available_balance),
                new DecimalFormat("########.########").format(availableBalance),
                symbol)
        );
    }

    // 选择买卖盘条目数据
    public void selectBuySellData(EntrustQueue.DataBean.Bean bean) {
        // 当用户选择状态不为市价时，更新.
        if (mEntrustType == C.API_LIMITED_PRICE) {
            if (mTransactionType == C.API_ENTRUST_BUY) {
                mSelectBuyData = bean;
            } else {
                mSelectSellData = bean;
            }

            loadSelectBuyOrPurchasableOrder();
        }
    }

    // 切换委托类型
    public void toggleEntrustType(int type) {
        mEntrustType = type;
        loadSelectBuyOrPurchasableOrder();
    }

    // 切换交易类型：买入、卖出
    public void toggleTransactionType(int type) {
        mTransactionType = type;
        loadSelectBuyOrPurchasableOrder();
    }


    public MutableLiveData<Resource<BaseResponseModel>> entrustOrders(
            String onPrice, String number) {
        Resources resources = getApplication().getResources();
        if (Strings.isEmpty(onPrice)) {
            mEntrustOrdersLiveData.setValue(Resource.error(resources.getString(R.string.please_enter_price)));
            return mEntrustOrdersLiveData;
        }

        if (Strings.isEmpty(number)) {
            mEntrustOrdersLiveData.setValue(Resource.error(resources.getString(R.string.please_enter_quantity)));
            return mEntrustOrdersLiveData;
        }

        double onPriceDouble = Double.parseDouble(onPrice);
        double numberDouble = Double.parseDouble(number);

        if (onPriceDouble <= 0) {
            mEntrustOrdersLiveData.setValue(Resource.error(resources.getString(R.string.please_enter_correct_price)));
            return mEntrustOrdersLiveData;
        }

        if (numberDouble <= 0) {
            mEntrustOrdersLiveData.setValue(Resource.error(resources.getString(R.string.please_enter_correct_quantity)));
            return mEntrustOrdersLiveData;
        }

        int uid = Androids.LocalConfig.getUid();
        String token = Androids.LocalConfig.getToken();
        String nonce = UUID.randomUUID().toString();

        // 加密串
        String sign = EncryptionUtils.generateEntrustOrdersSign(uid, token, mSymbol, mTransactionType,
                onPriceDouble, mEntrustType, numberDouble, nonce);

        mEntrustOrdersLiveData.setValue(Resource.loading());

        if (mTransactionType == C.API_ENTRUST_BUY){
            numberDouble = onPriceDouble * numberDouble;
        }

        DataRepository.get().entrustOrder(
                uid, token, mSymbol, mTransactionType, onPriceDouble, mEntrustType, numberDouble, sign, nonce, result -> {
                    if (result.isSucceed()) {
                        mEntrustOrdersLiveData.setValue(Resource.success(result, result.getMsg()));
                    } else {
                        mEntrustOrdersLiveData.setValue(Resource.error(result.getMsg()));
                    }
                });

        return mEntrustOrdersLiveData;
    }
}
